package com.mou.websocket;

import com.mou.entity.OnlineUser;
import com.mou.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ServerEndpoint("/ws/{userId}")
public class WebSocketServer {
    private static final ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        log.info("用户{}连接成功", userId);
        sessionMap.put(userId, session);
    }

    @OnMessage
    public void onMessage(String message, @PathParam("userId") String userId) {
        log.info("收到用户{}的消息: {}", userId, message);
    }

    @OnClose
    public void onClose(@PathParam("userId") String userId) {
        log.info("用户{}断开连接", userId);
        sessionMap.remove(userId);
    }

    // 向指定用户发送消息
    public static void sendMessageToUser(String userId, String message) {
        Session session = sessionMap.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                log.error("向用户{}发送消息失败: {}", userId, e.getMessage());
            }
        }
    }

    // 群发
    public static void broadcast(String message) {
        sessionMap.forEach((userId, session) -> {
            if (session.isOpen()) {
                session.getAsyncRemote().sendText(message);
            }
        });
    }
}